package com.p7.framework.permission.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class ClientShiroRealm extends AuthorizingRealm {

    /**
     * 获取权限信息，接口具有@RequiresPermissions注解或调用Subject#isPermitted方法时会调用此方法
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // TODO principals.getPrimaryPrincipal() 获取用户标识，去查询用户的权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permissions = new HashSet<String>();
        permissions.add("/test/permission");
        permissions.add("/test/logout");
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 从数据库等数据源中获取用户信息，返回的AuthenticationInfo在CredentialsMatcher中进行匹配
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        // TODO 通过username查询数据库中的数据，从数据库中获取用户信息，并封装用户标识和用户密码

        Long userId = 1L;
        String password = "111111";
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userId
                ,
                password,
                null,
                getName()
        );
        return authenticationInfo;
    }
}
